import re
from django.shortcuts import render, redirect
from rest_framework.views import APIView
from django.http import JsonResponse
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from powers_of_ten.utils.qiniuyun.qiniu_storage import storage
from django.conf import settings

from question.models import Label
from .models import User
from powers_of_ten.utils.fastdfs.fastdfs_storage import FastDFSStorage

from .serializers import UserSerializer
import json
import logging

logger = logging.getLogger('django')


# 利用七牛云上传图片,返回图片地址
class AvatarView(APIView):
    # permission_classes = [IsAuthenticated]

    def post(self, request):
        data = request.FILES.get('img')

        res = data.read()

        # key : 访问七牛获取图片的路径
        key = storage(res)

        url = settings.QINIU_URL + key
        # request.user.avatar = url
        # try:
        #     request.user.save()
        # except Exception as e:
        #     return JsonResponse({'errmsg': '上传失败', 'code': '400'})
        return JsonResponse({
            'imgurl': url
        })


# 用户登录后获取用户信息或修改用户信息
class UserCenterView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = User.objects.get(id=request.user.id)
        serializers = UserSerializer(instance=user)
        return Response(serializers.data)

    def put(self, request):
        user_of_backend = User.objects.get(pk=request.user.id)
        user_of_front = request.data
        bs = UserSerializer(instance=user_of_backend, data=user_of_front, partial=True)
        if not bs.is_valid():
            return Response(bs.errors, status=status.HTTP_400_BAD_REQUEST)

        try:
            bs.save()
        except Exception as e:
            logger.info(e)
            return Response(status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)


# 用户修改密码/user/password/  PUT
class ChangePasswordView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request):
        rec_pwd = json.loads(request.body.decode()).get('password')
        if not rec_pwd:
            return Response(status=status.HTTP_204_NO_CONTENT)

        if not re.match(r'^[0-9A-Za-z]{8,20}$', rec_pwd):
            return Response(status=status.HTTP_403_FORBIDDEN)

        try:
            request.user.set_password(rec_pwd)
            request.user.save()
        except Exception as e:
            logger.info(e)
            return Response(status=status.HTTP_408_REQUEST_TIMEOUT)
        return Response(status=status.HTTP_200_OK)


#用户关注他人和取关他人 users/like/{id}/  POST
class UserLikeView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        user = User.objects.get(id=request.user.id)
        add_fans = User.objects.get(id=pk)
        try:
            user.fans.add(add_fans)
        except Exception as e:
            logger.info(e)
            return Response({
                'message': '添加失败',
                'success': False
            })
        return Response({
            'message': 'OK',
            'success': True
        })

    def delete(self, request, pk):
        user = User.objects.get(id=request.user.id)
        rem_fans = User.objects.get(id=pk)

        try:
            user.fans.remove(rem_fans)
        except Exception as e:
            logger.info(e)
            return Response({
                'message': '取消失败',
                'success': False
            })
        return Response({
            'message': 'OK',
            'success': True
        })

from django.http import response
from django.views import View
# 富文本上传图片,并重定向.
class CkEditorView(APIView):
    """前端富文本编辑器上传图片"""
    # def post(self, request):
    #     data = request.FILES.get('img')
    #     res = data.read()
    #     key = storage(res)
    #     url = settings.QINIU_URL + key
    #
    #     return redirect('http://www.1024.site:8080/upload_success.html?image_url=' + url + '&CKEditorFuncNum=1')

    def post(self, request):
        rec_data = request.FILES.get('upload')
        ret = FastDFSStorage.save(self, name='name.jpg', content=rec_data)
        image_url = FastDFSStorage.url(self, ret)
        print(ret)
        url = 'http://www.1024.site:8080/upload_success.html?image_url=' + image_url + '&CKEditorFuncNum=1'

        # return response.HttpResponseRedirect(url)
        return redirect(url)

# 用户标签添加
class UserLabelView(APIView):

    def put(self, request):
        user_from_front = User.objects.get(pk=request.user.id)
        user_from_front.labels.clear()
        label_list = request.data.get('labels')
        try:
            for i in label_list:
                label = Label.objects.get(pk=i)
                label.users.add(user_from_front)

        except Exception as e:
            return Response(status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)


